package business

import (
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/business"
	"gorm.io/gorm"
)

type AnswerService struct {
}

// 添加答题
func (answerService AnswerService) CreatedAnswer(answerList []*business.Answer, questionnaireUuid string, phone string) (err error) {
	db := global.GVA_DB
	err = db.Transaction(func(tx *gorm.DB) error {
		//创建电话答题人
		people := business.People{
			Phone:             phone,
			QuestionnaireUuid: phone,
		}
		err = global.GVA_DB.Create(&people).Error
		if err != nil {
			return err
		}
		//指定答题卷修改状态
		err = tx.Model(&business.Invitation{}).Where("questionnaire_uuid = ? and phone = ?", questionnaireUuid, phone).Update("st", 3).Error
		if err != nil {
			return err
		}
		for k, _ := range answerList {
			answerList[k].QuestionnaireUuid = questionnaireUuid
			answerList[k].PeopleId = people.ID
			answerList[k].St = 1
		}
		err = global.GVA_DB.Create(&answerList).Error
		if err != nil {
			return err
		}
		return nil
	})

	return err
}

// 添加答题并提交
func (answerService AnswerService) CreatedAnswerSubmit(answerList []*business.Answer, questionnaireUuid string, phone string) (err error) {
	db := global.GVA_DB
	err = db.Transaction(func(tx *gorm.DB) error {
		//添加
		err = tx.Create(&answerList).Error
		if err != nil {
			return err
		}
		//创建电话答题人
		people := business.People{
			Phone:             phone,
			QuestionnaireUuid: phone,
		}
		err = global.GVA_DB.Create(&people).Error
		if err != nil {
			return err
		}
		//指定答题卷修改状态
		err = tx.Model(&business.Invitation{}).Where("questionnaire_uuid = ? and phone = ?", questionnaireUuid, phone).Update("st", 3).Error
		if err != nil {
			return err
		}
		for k, _ := range answerList {
			answerList[k].QuestionnaireUuid = questionnaireUuid
			answerList[k].PeopleId = people.ID
			answerList[k].St = 1
		}
		//修改状态
		err = tx.Model(&business.Answer{}).Where("questionnaire_uuid = ?", questionnaireUuid).Update("st", 1).Error
		if err != nil {
			return err
		}
		return nil
	})
	return nil
}

// 查询评分问卷的信息
func (answerService AnswerService) QueryAnswerByEnterprise(questionnaireUuid string) (answerList []*business.Answer, err error) {
	db := global.GVA_DB

	err = db.Where("questionnaire_uuid = ? ", questionnaireUuid).Find(&answerList).Error
	return answerList, err
}
